package com.lumlord.common.log;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Value;

import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.LayoutBase;


/**
   * 重构采集视图
 * @author win 10
 *
 */
public class LogstashLayOut extends LayoutBase<ILoggingEvent> {
	private  String appName;

	@Override
	public String doLayout(ILoggingEvent event) {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"projectName\":");
		sb.append("\"" + appName + "\", ");
		sb.append("\"timeStamp\":");
		sb.append("\"").append(new Timestamp(event.getTimeStamp())).append("\"");
		sb.append(", \"level\":");
		sb.append("\"").append(event.getLevel()).append("\"");
		sb.append(", \"threadName\":");
		sb.append("\"").append(event.getThreadName()).append("\"");
		sb.append(", \"class\": ");
		sb.append("\"").append(event.getLoggerName()).append("\"");
		sb.append(",\"message\": ");
		String message = event.getFormattedMessage();
		if (event.getThrowableProxy() != null) {
			ExtendedThrowableProxyConverter throwableConverter = new ExtendedThrowableProxyConverter();
			throwableConverter.start();
			message = event.getFormattedMessage() + "\n" + throwableConverter.convert(event);
			throwableConverter.stop();
		}
		int beginIndex = message.indexOf("{");
		int endIndex = message.lastIndexOf("}") + 1;
		if (beginIndex >= 0 && endIndex >= 0) {
			String Additional = message.substring(0, beginIndex);
			String jsonMsg = message.substring(beginIndex, endIndex);
			sb.append(jsonMsg);
			sb.append(",\"Additional\": ");
			sb.append("\"").append(Additional).append("\"");
			
			sb.append(","+message.substring(beginIndex+1, endIndex-1));
		} else {
			sb.append("\"").append(message).append("\"");
		}
		sb.append("}");
		sb.append(CoreConstants.LINE_SEPARATOR);
		System.out.println(sb.toString());
		return sb.toString();
	}

	public void setAppName(String appName) {
		this.appName = appName;
	}
}